import type { Metadata as MetadataNext } from 'next';
import { createError, getMetadata, isNum } from '@/lib/tool';
import { getTranslatedFields } from '@/lib/dictionaries';
import { authMiddleware } from '@/lib/api';
import { cookies } from 'next/headers';
import {
  queryPath,
  queryPostDetails,
  serverQueryAllChildReplyByReplyId,
} from '@/services/api';
import type {
  IChildReply,
  IPagination,
  IPath,
  IQueryPostDetails,
} from '@/interfaces';
import ResetPage from '@/app/[locale]/reset/reset';
import { notFound } from 'next/navigation';
import ChildReplyReplyAdminPage from '@/app/[locale]/admin/forum/reply/child-reply/child-reply';
import { getTranslator } from 'next-intl/server';

export async function generateMetadata({
  params: { locale },
}: {
  params: {
    locale: string;
  };
}): Promise<MetadataNext> {
  const t = await getTranslator(locale);
  return getMetadata({ title: t('replyAdminPage.title.childReply') });
}

async function getData(pid: string, cid: string, rid: string, prid: string) {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = queryPostDetails({
      baseURL: process.env.APP_API_SERVER,
      token,
      id: pid,
    });
    const req3 = serverQueryAllChildReplyByReplyId({
      baseURL: process.env.APP_API_SERVER,
      token,
      id: prid,
    });

    const responses = await Promise.all([req1, req2, req3]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();
    const resp3 = await ((await responses[2]) as Response).json();

    return {
      isSuccess: true,
      isError: false,
      path: resp1.data as IPath,
      info: resp2.data as IQueryPostDetails,
      list: resp3.data as IPagination<IChildReply>,
    };
  } catch (e: any) {
    return {
      isSuccess: false,
      isError: true,
      error: e,
    };
  }
}

export default async function Page({
  params: { locale },
  searchParams: { pid, cid, rid, prid },
}: {
  params: { locale: string };
  searchParams: { pid: string; cid: string; rid: string; prid: string };
}) {
  if (
    !pid ||
    !isNum(pid) ||
    !cid ||
    !isNum(cid) ||
    !rid ||
    !isNum(rid) ||
    !prid ||
    !isNum(prid)
  ) {
    notFound();
  }

  const data = await getData(pid, cid, rid, prid);
  if (data.isError) {
    return <ResetPage error={createError(data.error)} />;
  }

  const source = data.info!;
  const replies = data.list!;
  const translatedFields = await getTranslatedFields(locale, 'replyAdminPage');

  return (
    <ChildReplyReplyAdminPage
      prid={prid}
      rid={rid}
      cid={cid}
      source={source}
      replies={replies}
      translatedFields={translatedFields}
    />
  );
}
